import { Value } from '@radix-ui/react-select'
import { debug } from 'console'
import { cloneDeep } from 'lodash'
import { V } from 'react-router/dist/development/fog-of-war-BaM-ohjc'

/**
 * 保存graph的结构转换为运行的graph结构
 */
export const graphToRunGraph = (flow, graph) => {
  console.log('=============graphToRunGraph: flow, graph:', flow, graph)
  const newGraph = cloneDeep(graph)
  newGraph.nodes.forEach(item => {
    const type = item.data?.type
    const baseData = getBaseNodeDataInfo(item.data)
    if (type === 'start') {
      item.data = {
        ...baseData,
        ...startToRunStart(item.data.variables)
      }
    } else if (type === 'end') {
      // 结束节点
      item.data = {
        ...baseData,
        ...endToRunEnd(item.data)
      }
    } else if (type === 'llm') {
      // 大模型
      item.data = {
        ...baseData,
        ...llmToRunLlm(item.data)
      }
    } else if (type === 'tool') {
      // 插件
      item.data = {
        ...baseData,
        ...ToolToRunTool(item.data)
      }
    } else if (type === 'qa_retriever') {
      // 知识库
      item.data = {
        ...baseData,
        ...knowledgeToRunKnowledge(item.data)
      }
    } else if (type === 'code') {
      // 代码
      item.data = {
        ...baseData,
        ...CodeToRunCode(item.data)
      }
    } else if (type === 'if-else') {
      // 选择器
      item.data = {
        ...baseData,
        ...ElseIfRunTool(item.data)
      }
    } else if (type === 'intend') {
      // 意图识别
      item.data = {
        ...baseData,
        ...IntendRunTool(item.data)
      }
    } else if (type === 'doc_extractor'){
      // 文档提取
      item.data = {
        ...baseData,
        ...DocExtractorRunTool(item.data)
      }
    }else if (type === 'http_request'){
      // 文档提取
      item.data = {
        ...baseData,
        ...HttpRequestRunTool(item.data)
      }
    }else if (type === 'text_concatenation'){
      // 文本拼接
      item.data = {
        ...baseData,
        ...TextConcatenationRunTool(item.data)
      }
    }else if (type === 'var_update'){
      // 变量更新
      item.data = {
        ...baseData,
        ...VarUpdateRunTool(item.data)
      }
    }else if (type === 'iteration'){
      // 变量更新
      item.data = {
        ...baseData,
        ...IterationRunTool(item.data)
      }
    }else if (type === 'iteration_start'){
      // 变量更新
      item.data = {
        ...baseData,
        ...IterationStartRunTool(item.data)
      }
    }else if (type === 'iteration_end'){
      // 变量更新
      item.data = {
        ...baseData,
        ...IterationEndRunTool(item.data)
      }
    }else if (type === 'list'){
      // 变量更新
      item.data = {
        ...baseData,
        ...ListRunTool(item.data)
      }
    }else if (type === 'loop'){
      // 变量更新
      item.data = {
        ...baseData,
        ...LoopRunTool(item.data)
      }
    }else if (type === 'loop_start'){
      // 变量更新
      item.data = {
        ...baseData,
        ...LoopStartRunTool(item.data)
      }
    }else if (type === 'loop_end'){
      // 变量更新
      item.data = {
        ...baseData,
        ...LoopEndRunTool(item.data)
      }
    }
  })
  console.log('=============graphToRunGraph: newGraph:', { ...getFlowDataInfo(flow), ...newGraph })
  return { action: 'init_data', data: { ...getFlowDataInfo(flow), ...newGraph } }
}

/**
 * flow基础信息转换
 */
const getFlowDataInfo = flow => {
  return {
    id: flow.id,
    name: flow.name,
    status: flow.status,
    logo: flow.logo,
    guide_word: '',
    description: flow.description
  }
}

/**
 * node基础信息转换
 */
const getBaseNodeDataInfo = data => {
  return {
    id: data.id,
    name: data.title,
    type: data.type,
    description: data.desc
  }
}

function replaceInString(str, variableMap) {
  return str.replace(/{{(\w+)}}/g, (match, variable) => {
    if (variable in variableMap) {
      const inputItem = variableMap[variable]
      if (inputItem.type === 'cite' && inputItem.value_selector && inputItem.value_selector.length > 0) {
        return `{{#${inputItem.value_selector.join('.')}#}}`
      } else if (inputItem.type === 'input') {
        return inputItem.value
      }
    }
    return match
  })
}

/**
 * start的参数转为run_graph接收的参数
 * 1、将variables作为参数添加group_params[1].params[1].value
 * variables中的variable转为key，label转为value
 * 2、start的data添加startNodeParams，
 */
const startToRunStart = variables => {
  if (!variables || variables.length === 0) {
    return getRunStartNodeParams([])
  }

  const newParams = variables.map(variable => ({
    id: variable.id, // 或者使用其他方式生成唯一 ID
    key: variable.variable,
    type: variable.type,
    // type: variable.type,
    value: variable.label,
    required: variable.required,
    multi: false, // 根据需求设置
    options: [] // 根据需求设置
  }))
  const runStartParams = getRunStartNodeParams(newParams)
  return runStartParams
}

/**
 * 将end节点outputs中的value_selector数据，拼接为下方的数据格式{{#${nodeId}.${variable}#}}格式
 * type为text时直接使用outputText数据
 */
const endToRunEnd = data => {
  let runEndParams = getRunEndNodeParams('', 'outputs', [])
  if (!data.outputs || data.outputs.length === 0) {
    return runEndParams
  }

  const varMap = data.outputs
    .filter(item => item.value)
    .map(output => ({
      type: output.type,
      variable: output.variable,
      value: output.value.replace(',', '.'),
      value_selector: output.value_selector
    }))

  if (data.outputType === 'text') {
    const variableMap = data.outputs.reduce((acc, item) => {
      acc[item.variable] = item
      return acc
    }, {})
    const outputText = replaceInString(data.outputText, variableMap)
    runEndParams = getRunEndNodeParams(outputText, 'text', varMap)
  } else {
    const templateParts = []

    data.outputs.forEach(output => {
      const [nodeId, value] = output.value_selector || [undefined, undefined]
      if (nodeId && value) {
        templateParts.push(`${output.variable}:{{#${nodeId}.${value}#}}`)
      }
    })
    runEndParams = getRunEndNodeParams(templateParts.join('\n'), 'outputs', varMap)
  }
  return runEndParams
}

// 将大模型输入，用户提示词，系统提示词进行替换
function replaceLlmVariables(data) {
  // 处理 inputList 中的引用类型
  data.inputList = data.inputList.map(item => {
    if (item.type === 'cite' && item.valuet) {
      return {
        ...item,
        value: item.valuet,
        value_selector: item.valuet.split(',')
      }
    }
    return item
  })

  const variableMap = data.inputList.reduce((acc, item) => {
    acc[item.variable] = item
    return acc
  }, {})

  // 对callWord和userInput智能体replaceInString函数
  data.callWord = replaceInString(data.callWord, variableMap)
  data.userInput = replaceInString(data.userInput, variableMap)

  return data
}
/**
 * llm节点数据转换
 */
const llmToRunLlm = data => {
  const newData = replaceLlmVariables(data)
  const { model, callWord, userInput } = { ...newData }
  const runLlmParams = getRunLlmNodeParams(model.name, model.completion_params?.temperature, callWord, userInput)
  return runLlmParams
}

/* 插件数据转换 */
const ToolToRunTool = data => {
  // 构建输入列表
  const inputList = data.inputList.map(item => {
    const itemValue = item.value || item.valuet;
    return {
      key: item.variable,
      value: item.type === 'cite' ? `{{#${itemValue.replace(',', '.')}#}}` : itemValue,
      variable: item.variable,
      required: item.required
    }
  })
  // 构建模板信息
  const group_params = [
    {
      name: '工具ID',
      params: [
        {
          key: 'tool_id',
          type: 'var',
          label: 'tool_id',
          value: data.model?.id,
          required: true
        }
      ]
    },
    {
      name: '工具父节点ID',
      params: [
        {
          key: 'parent_tool_id',
          type: 'var',
          label: 'parent_tool_id',
          value: data.parent_tool_id,
          required: true
        }
      ]
    },
    {
      name: '输出',
      params: [
        {
          key: 'tool_output',
          type: 'var',
          label: '输出变量',
          value: '',
          global: 'key'
        }
      ]
    }
  ]
  if (inputList && inputList.length > 0) {
    group_params.splice(1, 0, {
      name: data.model?.name,
      params: inputList
    })
  }

  const { id, type, width, height, dragging, position, selected, positionAbsolute } = data
  const obj = {
    name: '工具',
    description: data.desc,
    expand: true,
    group_params,
    id,
    type,
    width,
    height,
    dragging,
    position,
    selected,
    positionAbsolute
  }
  return obj
}

/* 选择器数据转换 */
const ElseIfRunTool = data => {
  const list = data.ifList.map(item => ({
    id: item.case_id,
    operator: item.ifType,
    conditions: item.inputList.map(IfItem => ({
      id: IfItem.id,
      right_value_type: IfItem?.type === 'cite' ? 'ref' : IfItem.type,
      left_var: IfItem?.variable?.replace(',', '.'),
      left_label: IfItem?.variable?.replace(',', '.'),
      right_value: IfItem.type === 'cite' ? IfItem?.value?.replace(',', '.') : IfItem.value,
      right_label: IfItem.type === 'cite' ? IfItem?.value?.replace(',', '.') : IfItem.value,
      comparison_operation: IfItem.conditions
    }))
  }))

  const { id, width, height, dragging, position, selected, positionAbsolute } = data
  const obj = {
    id,
    name: '条件分支',
    description: data.desc,
    // expand: true,
    group_params: [
      {
        params: [
          {
            key: 'condition',
            type: 'condition',
            label: '',
            value: list
          }
        ]
      }
    ],
    type: 'condition',
    width,
    height,
    dragging,
    position,
    selected,
    positionAbsolute
  }
  return obj
}

/* 意图识别数据转换 */
const IntendRunTool = data => {
  const { id, width, height, dragging, position, selected, positionAbsolute } = data
  const obj = {
    id,
    name: '意图理解',
    type: 'intention',
    description: data.desc,
    group_params: [
      {
        name: '模型设置',
        params: [
          {
            key: 'model_id',
            label: '模型',
            value: data.model.name
          },
          {
            key: 'temperature',
            step: 0.1,
            type: 'slide',
            label: '温度',
            scope: [0.1, 1],
            value: data.model.completion_params.temperature
          }
        ]
      },
      {
        name: '输入',
        params: [
          {
            key: 'variable',
            value: data.inputList.map(item => {
              let queryValue = item.value? item.value : item.valuet
              const itemType = item.type === 'cite' ? 'refer' : 'input'
              if (item.type === 'cite') {
                queryValue = queryValue.replace(',', '.')
              }
              return {
                type: itemType,
                value: queryValue
              }
            })
          }
        ]
      },
      {
        name: '意图匹配',
        params: [
          {
            key: 'intentions',
            type: 'intention',
            label: '',
            value: data.recognizeList.map(item => {
              return {
                ...item,
                description: item.variable
              }
            })
          }
        ]
      },
      {
        name: '提示词',
        params: [
          {
            key: 'system_prompt',
            test: 'input',
            type: 'var_textarea',
            label: '高级设置',
            value: data.userInput,
            required: true
          }
        ]
      }
    ],
    width,
    height,
    dragging,
    position,
    selected,
    positionAbsolute
  }
  return obj
}

/**
 * 知识库节点数据转换
 */
const knowledgeToRunKnowledge = data => {
  const queryInfo = data.inputList && data.inputList.length > 0 ? data.inputList[0] : {}
  let queryValue = queryInfo.value || queryInfo.valuet 

  if (queryInfo.type === 'cite') {
    queryValue = `{{#${queryValue.replace(',', '.')}#}}`
    // queryValue = queryInfo.value.replace(',', '.')
  }

  const knowledgeInfos = data.knowledgeList
    ? data.knowledgeList.map(item => {
        return { key: item.id, label: item.name }
      })
    : []
  const runLlmParams = getRunKnowledgeNodeParams(queryValue, knowledgeInfos)
  return runLlmParams
}

/**
 * 代码节点数据转换
 */
const CodeToRunCode = data => {
  return {
    group_params: [
      {
        name: '入参',
        params: [
          {
            key: 'code_input',
            test: 'input',
            type: 'code_input',
            value: data.inputList.map((it, index) => {
              let queryValue = it.value || it.valuet
              if (it.type === 'cite') {
                queryValue = queryValue.replace(',', '.')
              }
              return {
                key: it.variable,
                type: it.type === 'cite' ? 'ref' : 'input',
                label: `text_input${index + 1}`,
                value: queryValue
              }
            }),
            required: true
          }
        ]
      },
      {
        name: '执行代码',
        params: [
          {
            key: 'code',
            type: 'code',
            value: data.code,
            required: true
          }
        ]
      },
      {
        name: '出参',
        params: [
          {
            key: 'code_output',
            type: 'code_output',
            value: data.outputList.map(it => ({
              key: it.variable,
              type: it.type
            })),
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}

const getRunStartNodeParams = values => {
  return {
    tab: {
      value: 'form',
      options: [
        { key: 'input', help: '接收用户从对话框输入的内容', label: '对话框输入' },
        { key: 'form', help: '将会在用户会话界面弹出一个表单，接收用户从表单提交的内容', label: '表单输入' }
      ]
    },
    group_params: [
      {
        name: '全局变量',
        params: [
          { key: 'current_time', type: 'var', label: '当前时间', value: '', global: 'key' },
          { key: 'chat_history', type: 'chat_history_num', value: 10, global: 'key' },
          { key: 'preset_question', type: 'input_list', label: '预置问题列表', value: [''], global: 'index' }
        ]
      },
      {
        name: '输入',
        params: [
          { key: 'user_input', tab: 'input', type: 'var', global: 'key' },
          {
            key: 'form_input',
            tab: 'form',
            type: 'form',
            value: values,
            // value: [
            //   { key: 'text_input', type: 'text', value: 'input1', required: true, multi: false, options: [] },
            //   { key: 'text_input2', type: 'text', value: '输入2', required: true, multi: false, options: [] }
            // ],
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))'
          }
        ]
      }
    ]
  }
}

const getRunEndNodeParams = (outputMessage, outputType, varMap: []) => {
  return {
    group_params: [
      {
        params: [
          {
            key: 'output_msg',
            label: '消息内容',
            type: 'var_textarea_file',
            required: true,
            value: { msg: outputMessage, files: [] }
            // value: { msg: '{{#llm_17c4c.output#}}{{#flowNode_16514.output#}}', files: [] }
          },
          {
            key: 'output_map',
            label: '映射关系',
            type: 'var_textarea_file',
            required: true,
            value: {
              var_map: varMap
              // var_map: [
              //   {
              //     type: 'cite',
              //     variable: 'output',
              //     value: 'start 60d7C.AGENT_USER_INPUT',
              //     value_selector: ['start_60d7C', 'AGENT_USER_INPUT']
              //   }
              // ]
            },
            options: []
          },
          {
            key: 'output_type',
            label: '输出方式',
            type: 'var_textarea_file',
            required: true,
            value: {
              type: outputType // // # outputs | text
            },
            options: []
          },
          {
            key: 'output_result',
            label: '交互类型',
            global: 'value.type=input',
            type: 'output_form',
            required: true,
            value: { type: '', value: '' },
            options: []
          }
        ]
      }
    ]
  }
}

const getRunLlmNodeParams = (modelName, temperature, systemPrompt, userPrompt) => {
  return {
    tab: {
      value: 'single',
      options: [
        { key: 'single', label: '单次运行' },
        { key: 'batch', label: '批量运行' }
      ]
    },
    group_params: [
      {
        params: [
          {
            key: 'batch_variable',
            tab: 'batch',
            help: '选择需要批处理的变量，将会多次运行本节点，每次运行时从选择的变量中取一项赋值给batch_variable进行处理。',
            type: 'user_question',
            label: '批处理变量',
            value: [],
            global: 'self',
            linkage: 'output',
            required: true,
            placeholder: '请选择批处理变量'
          }
        ]
      },
      {
        name: '模型设置',
        params: [
          { key: 'model_id', value: modelName, label: '模型' },
          {
            key: 'temperature',
            step: 0.1,
            type: 'slide',
            label: '温度',
            scope: [0.1, 1],
            value: temperature
          }
        ]
      },
      {
        name: '提示词',
        params: [
          {
            key: 'system_prompt',
            test: 'input',
            type: 'var_textarea',
            label: '系统提示词',
            value: systemPrompt,
            required: true
          },
          {
            key: 'user_prompt',
            test: 'input',
            type: 'var_textarea',
            label: '用户提示词',
            value: userPrompt,
            required: true
          }
        ]
      },
      {
        name: '输出',
        params: [
          {
            key: 'output_user',
            help: '一般在问答等场景可开启，文档审核、报告生成等场景可关闭',
            type: 'switch',
            label: '将输出结果展示在会话中',
            value: false
          },
          {
            key: 'output',
            type: 'var',
            label: '输出变量',
            value: [],
            global: 'code:value.map(el => ({ label: el.label, value: el.key }))'
          }
        ]
      }
    ]
  }
}

const getRunKnowledgeNodeParams = (queryValue, knowledgeInfos) => {
  return {
    group_params: [
      {
        name: '检索设置',
        params: [
          {
            key: 'user_question',
            label: '输入变量',
            type: 'var',
            value: queryValue,
            required: true
          },
          {
            key: 'qa_knowledge_id',
            label: '知识库',
            type: 'list',
            value: knowledgeInfos, // [{"key":"", "label":""}]
            required: true
          }
        ]
      },
      {
        name: '输出',
        params: [
          {
            key: 'retrieved_result',
            label: '检索结果',
            type: 'var',
            global: 'key',
            value: ''
          }
        ]
      }
    ]
  }
}

const inputIsEmpty = (value): boolean => {
  if (!value && value != 0) {
    return true
  }
  return false
}

/**
 * 将运行内容拼接为指定结构
 */
export const inputToRunInput = (startNodeId, inputData, variables = []) => {
  const data = inputData || {}
  let inputMsg = ''
  variables.forEach(item => {
    if (!inputIsEmpty(item.label) && !inputIsEmpty(item.variable)) {
      inputMsg += `${item.label}:${data[item.variable]}\n`
    }
  })
  return {
    action: 'input',
    data: {
      [startNodeId]: {
        // data: { text_input: '你好啊', text_input2: '心情不错' },
        // message: 'input1:你好啊\n输入2:心情不错\n',
        data: inputData,
        message: inputMsg,
        message_id: '',
        category: 'question',
        extra: '',
        source: 0
      }
    }
  }
}

export const inputToRunInputIDAnd = (startNodeId, inputData, variables = []) => {
  const data = inputData || {}

  const updatedData = Object.fromEntries(
    Object.entries(inputData).map(([key, value]) => [`${startNodeId}.${key}`, value])
  )

  let inputMsg = ''
  variables.forEach(item => {
    inputMsg += `${item.label}:${data[item.variable]}\n`
  })

  return {
    action: 'input',
    data: {
      [startNodeId]: {
        data: updatedData,
        message: inputMsg,
        message_id: '',
        category: 'question',
        extra: '',
        source: 0
      }
    }
  }
}

// 添加文档提取器转换函数
const DocExtractorRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.type === 'cite' ? (item.value ? `{{#${item.value.replace(',', '.')}#}}` : `{{#${item.valuet.replace(',', '.')}#}}`) : item.value,
    variable: item.variable,
    required: true
  }))

  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    type: item.type || 'string',
    value: item.value
  }))

  return {
    group_params: [
      {
        name: '输入文档',
        params: [
          {
            key: 'doc_input',
            type: 'doc_input',
            value: inputList,
            required: true
          }
        ]
      },
      {
        name: '输出变量',
        params: [
          {
            key: 'doc_output',
            type: 'doc_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}


// 添加文档提取器转换函数
const HttpRequestRunTool = (data) => {
  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    type: item.type || 'string',
    value: item.value
  }))

  if (data.body.type === 'http_form_body') {
    data.body.content = data.body.content.map(item => ({
      key: item.key,
      value: item.type === 'cite'? `{{#${item.value.replace(',', '.')}#}}` : item.value,
      variable: item.type,
      required: true
    }))
  } else if (data.body.type === 'http_raw_body' 
    || data.body.type === 'http_json_body' 
    || data.body.type === 'http_xml_body') {
    data.body.content = data.body.content ? data.body.content.replace(/\{\{(.*?)\}\}/g, (match, value) => `{{#${value.replace(',', '.')}#}}`):data.body.content
  }
  data.url = data.url.replace(/\{\{(.*?)\}\}/g, (match, value) => `{{#${value.replace(',', '.')}#}}`)
  data.headers =  data.headers.filter(item => item.key && item.value)
  data.params =  data.params.filter(item => item.key && item.value)
  const httpRequestParams = {
    method: data.method,
    url: data.url,
    headers: data.headers,
    params: data.params,
    body: data.body,
    failure_retry: data.failureRetry, // 失败重试
    retry_times: data.retryTimes,
    retry_interval: data.retryInterval,
    connect_timeout: data.connectTimeout,
    read_timeout: data.readTimeout,
  }

  return {
    group_params: [
      {
        name: '输入文档',
        params: [
          {
            key: 'http_input',
            type: 'http_input',
            value: httpRequestParams,
            required: true
          }
        ]
      },
      {
        name: '输出变量',
        params: [
          {
            key: 'http_output',
            type: 'http_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}

// 添加文档提取器转换函数
const TextConcatenationRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.value.replace(/\{\{(.*?)\}\}/g, (match, value) => `{{#${value.replace(',', '.')}#}}`),
    variable: item.variable,
    required: true
  }))

  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    type: item.type || 'string',
    value: item.value
  }))

  return {
    group_params: [
      {
        name: '输入文档',
        params: [
          {
            key: 'text_input',
            type: 'text_input',
            value: inputList,
            required: true
          }
        ]
      },
      {
        name: '输出变量',
        params: [
          {
            key: 'text_output',
            type: 'text_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}


// 添加文档提取器转换函数
const VarUpdateRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.value.replace(/\{\{(.*?)\}\}/g, (match, value) => `{{#${value.replace(',', '.')}#}}`),
    variable: item.variable ? item.variable.replace(',', '.') : item.value,
    required: true
  }))

  
  return {
    group_params: [
      {
        name: '输入文档',
        params: [
          {
            key: 'var_update_input',
            type: 'var_update_input',
            value: inputList,
            required: true
          }
        ]
      }
    ]
  }
}

const IterationRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.type === 'cite' ? `{{#${item.value.replace(',', '.')}#}}` : item.value,
    variable: item.variable,
    required: true
  }))

  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    type: item.type || 'string',
    value: item.value
  }))

  return {
    group_params: [
      {
        name: '输入文档',
        params: [
          {
            key: 'iteration_input',
            type: 'iteration_input',
            value: inputList,
            required: true
          }
        ]
      },
      {
        name: '输出变量',
        params: [
          {
            key: 'iteration_output',
            type: 'iteration_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}

const IterationStartRunTool = (data) => {
  return {
    group_params: [
    ]
  }
}


const IterationEndRunTool = (data) => {
  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    variable: item.variable,
    type: item.type || 'string',
    value: item.type === 'cite' ? `{{#${item.value.replace(',', '.')}#}}` : item.value
  }))

  return {
    group_params: [
      {
        name: '输出变量',
        params: [
          {
            key: 'iteration_end_output',
            type: 'iteration_end_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}

const ListRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.type === 'cite' ? `{{#${item.value.replace(',', '.')}#}}` : item.value,
    variable: item.value,
    required: true,
    type: item.sourceType
  }))

  const inputAndFilterList = {
    filter: data.filter,
    take_top_n: data.takeTopN,
    take_n: data.takeN,
    sort: data.sort,
    input_list: inputList
  } 
  
  // 构建输出列表
  const outputList = data.outputList.map(item => ({
    key: item.variable,
    type: item.type || 'string',
    value: item.value
  }))

  return {
    group_params: [
      {
        name: '列表操作输入',
        params: [
          {
            key: 'list_input',
            type: 'list_input',
            value: inputAndFilterList,
            required: true
          }
        ]
      },
      {
        name: '列表操作输出变量',
        params: [
          {
            key: 'list_output',
            type: 'list_output',
            value: outputList,
            global: 'code:value.map(el => ({ label: el.key, value: el.key }))',
            required: true
          }
        ]
      }
    ]
  }
}
const LoopRunTool = (data) => {
  // 构建输入列表
  const inputList = data.inputList.map(item => ({
    key: item.variable,
    value: item.type === 'cite' ? `{{#${item.value.replace(',', '.')}#}}` : item.value,
    variable: item.variable,
    required: true,
    type: item.variableType
  }))

  data.filter.rules = data.filter.rules.map(item => ({
    key: item.variable,
    value: item.valueType === 'cite' ? (item.value ? `{{#${item.value.replace(',', '.')}#}}` : `{{#${item.valuet.replace(',', '.')}#}}`) : item.value,
    variable: `${item.variable.replace(',', '.')}`,
    required: true,
    operation: item.operation,
  }))

  const inputAndFilterList = {
    filter: data.filter,
    input_list: inputList,
    max_loop_times: data.max_loop_times,
  }
  

  return {
    group_params: [
      {
        name: '循环输入',
        params: [
          {
            key: 'loop_input',
            type: 'loop_input',
            value: inputAndFilterList,
            required: true
          }
        ]
      },
      {
        name: '循环输出变量',
        params: [
        ]
      }
    ]
  }
}

const LoopStartRunTool = (data) => {
  return {
    group_params: [
    ]
  }
}


const LoopEndRunTool = (data) => {
  // 构建输出列表
  return {
    group_params: [
    ]
  }
}




